import axios from "axios";
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'
let loadObj = null

//使用create 创建axios实例
const Service = axios.create({
    timeout: 8000,
    //baseURL: "/path1",//http://localhost:8090
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    },
})

//请求之前
Service.interceptors.request.use(config => {

    const accessToken = localStorage.getItem('TOKEN_DATA');
    if (accessToken) {
        config.headers.Authorization = accessToken;
    }
    loadObj = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
})

//响应拦截
Service.interceptors.response.use(response => {
    // loadObj.close()
    // return response
    loadObj.close()
    if (response.config.responseType === "blob" || response.config.responseType === "arraybuffer") {
        return response;
    }
    const { code, data, msg } = response.data;
    if (code == "200") {
        return data;
    }
    let lmsg = msg || "操作失败";
    ElMessage.error(lmsg);
    return Promise.reject(new Error(lmsg));
}, error => {
    loadObj.close()
    // const { code, msg } = error.response.data;
    // ElMessage.error(msg || "系统出错2");
    //return Promise.reject(error.message);
    return Promise.reject("系统出错");
})

//post请求

export const post = config => {
    return Service({
        ...config,
        method: "post",
        data: config.data
    })
}
//get请求

export const get = config => {
    return Service({
        ...config,
        method: "get",
        params: config.params
    })
}
